Self-Driving Car Engineer Nanodegree

Deep Learning

Project: Build a Traffic Sign Recognition Classifier

In this notebook, a template is provided for you to implement your functionality in stages which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission, if necessary. Sections that begin with 'Implementation' in the header indicate where you should begin your implementation for your project. Note that some sections of implementation are optional, and will be marked with 'Optional' in the header.

In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.


Step 0: Load The Data

In [28]:
# Usual imports
import numpy as np
import pandas as pd
from IPython.display import display # Allows the use of display() for DataFrames

# Load pickled data
import pickle

# Import Keras
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.constraints import maxnorm
from keras.optimizers import SGD
from keras.layers.convolutional import Convolution2D
from keras.layers.convolutional import MaxPooling2D
from keras.utils import np_utils
from keras import backend as K
K.set_image_dim_ordering('th')

# TODO: Fill this in based on where you saved the training and testing data

training_file = "./train.p"
testing_file = "./test.p"

with open(training_file, mode='rb') as f:
    train = pickle.load(f)
with open(testing_file, mode='rb') as f:
    test = pickle.load(f)
    
X_train, y_train = train['features'], train['labels']
X_test, y_test = test['features'], test['labels']

# Load class descriptions
signnames = pd.read_csv("signnames.csv")

print("Data loaded...")
Data loaded...

Step 1: Dataset Summary & Exploration

The pickled data is a dictionary with 4 key/value pairs:

  • 'features' is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).
  • 'labels' is a 2D array containing the label/class id of the traffic sign. The file signnames.csv contains id -> name mappings for each id.
  • 'sizes' is a list containing tuples, (width, height) representing the the original width and height the image.
  • 'coords' is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGES

Complete the basic data summary below.

In [29]:
### Replace each question mark with the appropriate value.

# TODO: Number of training examples
n_train = len(X_train)

# TODO: Number of testing examples.
n_test = len(X_test)

# TODO: What's the shape of an traffic sign image?
image_shape = X_train.shape

# TODO: How many unique classes/labels there are in the dataset.
n_classes = max(y_train) + 1

print("Number of training examples =", n_train)
print("Number of testing examples =", n_test)
print("Image data shape =", image_shape)
print("Number of classes =", n_classes)
Number of training examples = 39209
Number of testing examples = 12630
Image data shape = (39209, 32, 32, 3)
Number of classes = 43
In [30]:
# Display SignNames (class descriptions)
display(signnames)
ClassId SignName
0 0 Speed limit (20km/h)
1 1 Speed limit (30km/h)
2 2 Speed limit (50km/h)
3 3 Speed limit (60km/h)
4 4 Speed limit (70km/h)
5 5 Speed limit (80km/h)
6 6 End of speed limit (80km/h)
7 7 Speed limit (100km/h)
8 8 Speed limit (120km/h)
9 9 No passing
10 10 No passing for vechiles over 3.5 metric tons
11 11 Right-of-way at the next intersection
12 12 Priority road
13 13 Yield
14 14 Stop
15 15 No vechiles
16 16 Vechiles over 3.5 metric tons prohibited
17 17 No entry
18 18 General caution
19 19 Dangerous curve to the left
20 20 Dangerous curve to the right
21 21 Double curve
22 22 Bumpy road
23 23 Slippery road
24 24 Road narrows on the right
25 25 Road work
26 26 Traffic signals
27 27 Pedestrians
28 28 Children crossing
29 29 Bicycles crossing
30 30 Beware of ice/snow
31 31 Wild animals crossing
32 32 End of all speed and passing limits
33 33 Turn right ahead
34 34 Turn left ahead
35 35 Ahead only
36 36 Go straight or right
37 37 Go straight or left
38 38 Keep right
39 39 Keep left
40 40 Roundabout mandatory
41 41 End of no passing
42 42 End of no passing by vechiles over 3.5 metric ...

Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc.

The Matplotlib examples and gallery pages are a great resource for doing visualizations in Python.

NOTE: It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections.

In [31]:
### Data exploration visualization goes here.
### Feel free to use as many code cells as needed.
import matplotlib.pyplot as plt
from scipy.misc import toimage

# Visualizations will be shown in the notebook.
%matplotlib inline

Let us visualize dataset by plotting an image from each class.

In [32]:
# show an image from each class in a grid
plt.subplots(figsize=(20, 35))
row = 1
col = 1
for i in range(n_classes):
    
    class_id = np.where(y_train==i)[0][0]
    plt.subplot2grid((10, 6), (row, col)) # we really need 9 x 5 = 45 to cover 43 images. Keep one extra each
    plt.imshow(toimage(X_train[class_id]))
    plt.axis("off")
    title = signnames['SignName'][i]
    plt.title(title)
    
    col += 1
    if(col > 5): 
        col = 1
        row += 1

Let us plot histogram of training labels to visualize if there are any imbalances in class distribution

In [33]:
def show_samples_distribution():
    plt.hist(y_train, n_classes)
    plt.title('Number of samples per class')
    plt.xlabel('Class')
    plt.ylabel('Count')
    _ =  plt.show()
    
show_samples_distribution()

There is too much difference between the classes. We are going to create some data to balance the number of inputs and reduce the probable bias the network could have towards some classes. It will also help us give more data to our network.


Step 2: Design and Test a Model Architecture

Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the German Traffic Sign Dataset.

There are various aspects to consider when thinking about this problem:

  • Neural network architecture
  • Play around preprocessing techniques (normalization, rgb to grayscale, etc)
  • Number of examples per label (some have more than others).
  • Generate fake data.

Here is an example of a published baseline model on this problem. It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.

NOTE: The LeNet-5 implementation shown in the classroom at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play!

Implementation

Use the code cell (or multiple code cells, if necessary) to implement the first step of your project. Once you have completed your implementation and are satisfied with the results, be sure to thoroughly answer the questions that follow.

In [34]:
### Preprocess the data here.
### Feel free to use as many code cells as needed.
import cv2

print('Generating additional data...')

samples_per_class = np.bincount(y_train)
angles = [-3, 3, -5, 5, -10, 10, -15, 15, -20, 20]

image_cols = X_train.shape[1] # 32 x 32 image
image_rows = X_train.shape[2]

rotated_images = []
rotated_labels = []

# use openCV to rotate images of classes that have few samples

samples_count_in_max_class = max(samples_per_class)
for class_id in range(n_classes):
    samples_count_in_this_class = samples_per_class[class_id]
    shortfall = samples_count_in_max_class - samples_count_in_this_class
    
    image_ids_in_this_class = np.where(y_train == class_id)[0]
    for image_id in image_ids_in_this_class:
        for angle in angles:
            source_image = X_train[image_id]
            rotation_matrix = cv2.getRotationMatrix2D((image_cols/2, image_rows/2), angle, 1)
            rotated_image = cv2.warpAffine(source_image, rotation_matrix, (image_cols, image_rows))
            
            rotated_images.append(rotated_image)
            rotated_labels.append(class_id)
            
            shortfall -= 1
            if(shortfall <= 0): break
            # plt.imshow(toimage(source_image))
            # plt.imshow(toimage(rotated_image))
        if(shortfall <= 0): break

print ("Finished rotating images")

# Concatenate generated data with loaded dataset
X_train = np.append(X_train, rotated_images, axis=0)
y_train = np.append(y_train, rotated_labels, axis=0)

# histogram with augumented data
show_samples_distribution()

# Normalize features from 0-255 to 0.0-1.0
X_train = X_train / 255.0
X_test = X_test / 255.0
print ("Finished normalizing images")

# one hot encode outputs
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
print ("Finished one hot encoding labels")

# Get randomized datasets for training and validation
from sklearn.model_selection import train_test_split
X_train, X_validation, y_train, y_validation = train_test_split(
   X_train,
   y_train,
   test_size=0.2,
   random_state=7
)
print('Finished randomizing and splitting dataset into train and validation')
Generating additional data...
Finished rotating images
Finished normalizing images
Finished one hot encoding labels
Finished randomizing and splitting dataset into train and validation

Ah! The data looks more balanced now. Let us use it to train our Neural Network Classifier.

Convolutional Neural Network to classify Traffic Signs

We will use a structure with two convolutional layers followed by max pooling and a flattening out of the network to fully connected layers to make predictions.

Our baseline network structure can be summarized as follows:

  • Convolutional input layer, 32 feature maps with a size of 3×3, a rectifier activation function and a weight constraint of max norm set to 3.
  • Dropout set to 20%.
  • Convolutional layer, 32 feature maps with a size of 3×3, a rectifier activation function and a weight constraint of max norm set to 3.
  • Max Pool layer with size 2×2.
  • Flatten layer.
  • Fully connected layer with 512 units and a rectifier activation function.
  • Dropout set to 50%.

Fully connected output layer with 43 units and a softmax activation function.

A logarithmic loss function is used with the stochastic gradient descent optimization algorithm configured with a large momentum and weight decay start with a learning rate of 0.01.

In [35]:
# Create the model
model = Sequential()
model.add(Convolution2D(32, 3, 3, input_shape=(32, 32, 3), border_mode='same', activation='relu', W_constraint=maxnorm(3)))
model.add(Dropout(0.2))
model.add(Convolution2D(32, 3, 3, activation='relu', border_mode='same', W_constraint=maxnorm(3)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(512, activation='relu', W_constraint=maxnorm(3)))
model.add(Dropout(0.5))
model.add(Dense(n_classes, activation='softmax'))

# Compile model
epochs = 25
lrate = 0.01
decay = lrate/epochs
sgd = SGD(lr=lrate, momentum=0.9, decay=decay, nesterov=False)
model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
print(model.summary())
____________________________________________________________________________________________________
Layer (type)                     Output Shape          Param #     Connected to                     
====================================================================================================
convolution2d_5 (Convolution2D)  (None, 32, 32, 3)     9248        convolution2d_input_4[0][0]      
____________________________________________________________________________________________________
dropout_7 (Dropout)              (None, 32, 32, 3)     0           convolution2d_5[0][0]            
____________________________________________________________________________________________________
convolution2d_6 (Convolution2D)  (None, 32, 32, 3)     9248        dropout_7[0][0]                  
____________________________________________________________________________________________________
maxpooling2d_3 (MaxPooling2D)    (None, 32, 16, 1)     0           convolution2d_6[0][0]            
____________________________________________________________________________________________________
flatten_3 (Flatten)              (None, 512)           0           maxpooling2d_3[0][0]             
____________________________________________________________________________________________________
dense_7 (Dense)                  (None, 512)           262656      flatten_3[0][0]                  
____________________________________________________________________________________________________
dropout_8 (Dropout)              (None, 512)           0           dense_7[0][0]                    
____________________________________________________________________________________________________
dense_8 (Dense)                  (None, 43)            22059       dropout_8[0][0]                  
====================================================================================================
Total params: 303211
____________________________________________________________________________________________________
None

We can fit this model with 25 epochs and a batch size of 32.

Once the model is fit, we evaluate it on the test dataset and print out the classification accuracy.

In [36]:
# Fit the model
history = model.fit(X_train, y_train, validation_data=(X_validation, y_validation), nb_epoch=epochs, batch_size=32)

# Final evaluation of the model
scores = model.evaluate(X_test, y_test, verbose=0)
print("Accuracy: %.2f%%" % (scores[1]*100))
Train on 77400 samples, validate on 19351 samples
Epoch 1/25
77400/77400 [==============================] - 83s - loss: 1.0605 - acc: 0.6936 - val_loss: 0.1932 - val_acc: 0.9506
Epoch 2/25
77400/77400 [==============================] - 83s - loss: 0.2652 - acc: 0.9202 - val_loss: 0.1023 - val_acc: 0.9729
Epoch 3/25
77400/77400 [==============================] - 81s - loss: 0.1695 - acc: 0.9488 - val_loss: 0.0797 - val_acc: 0.9811
Epoch 4/25
77400/77400 [==============================] - 80s - loss: 0.1316 - acc: 0.9606 - val_loss: 0.0551 - val_acc: 0.9871
Epoch 5/25
77400/77400 [==============================] - 84s - loss: 0.1086 - acc: 0.9674 - val_loss: 0.0486 - val_acc: 0.9895
Epoch 6/25
77400/77400 [==============================] - 84s - loss: 0.0932 - acc: 0.9718 - val_loss: 0.0423 - val_acc: 0.9908
Epoch 7/25
77400/77400 [==============================] - 82s - loss: 0.0832 - acc: 0.9753 - val_loss: 0.0399 - val_acc: 0.9916
Epoch 8/25
77400/77400 [==============================] - 83s - loss: 0.0762 - acc: 0.9770 - val_loss: 0.0376 - val_acc: 0.9916
Epoch 9/25
77400/77400 [==============================] - 84s - loss: 0.0699 - acc: 0.9792 - val_loss: 0.0354 - val_acc: 0.9927
Epoch 10/25
77400/77400 [==============================] - 85s - loss: 0.0670 - acc: 0.9800 - val_loss: 0.0339 - val_acc: 0.9930
Epoch 11/25
77400/77400 [==============================] - 81s - loss: 0.0621 - acc: 0.9814 - val_loss: 0.0323 - val_acc: 0.9932
Epoch 12/25
77400/77400 [==============================] - 79s - loss: 0.0595 - acc: 0.9823 - val_loss: 0.0316 - val_acc: 0.9934
Epoch 13/25
77400/77400 [==============================] - 83s - loss: 0.0559 - acc: 0.9831 - val_loss: 0.0309 - val_acc: 0.9936
Epoch 14/25
77400/77400 [==============================] - 79s - loss: 0.0552 - acc: 0.9839 - val_loss: 0.0298 - val_acc: 0.9940
Epoch 15/25
77400/77400 [==============================] - 80s - loss: 0.0529 - acc: 0.9847 - val_loss: 0.0296 - val_acc: 0.9944
Epoch 16/25
77400/77400 [==============================] - 81s - loss: 0.0532 - acc: 0.9844 - val_loss: 0.0286 - val_acc: 0.9946
Epoch 17/25
77400/77400 [==============================] - 81s - loss: 0.0505 - acc: 0.9853 - val_loss: 0.0279 - val_acc: 0.9943
Epoch 18/25
77400/77400 [==============================] - 81s - loss: 0.0476 - acc: 0.9863 - val_loss: 0.0273 - val_acc: 0.9949
Epoch 19/25
77400/77400 [==============================] - 84s - loss: 0.0466 - acc: 0.9861 - val_loss: 0.0278 - val_acc: 0.9950
Epoch 20/25
77400/77400 [==============================] - 84s - loss: 0.0458 - acc: 0.9864 - val_loss: 0.0270 - val_acc: 0.9947
Epoch 21/25
77400/77400 [==============================] - 84s - loss: 0.0455 - acc: 0.9867 - val_loss: 0.0268 - val_acc: 0.9950
Epoch 22/25
77400/77400 [==============================] - 85s - loss: 0.0446 - acc: 0.9869 - val_loss: 0.0261 - val_acc: 0.9950
Epoch 23/25
77400/77400 [==============================] - 84s - loss: 0.0439 - acc: 0.9869 - val_loss: 0.0256 - val_acc: 0.9955
Epoch 24/25
77400/77400 [==============================] - 84s - loss: 0.0430 - acc: 0.9875 - val_loss: 0.0255 - val_acc: 0.9953
Epoch 25/25
77400/77400 [==============================] - 84s - loss: 0.0411 - acc: 0.9878 - val_loss: 0.0261 - val_acc: 0.9950
Accuracy: 91.24%

We can use the data collected in the history object to create plots.

In [39]:
# list all data in history
print(history.history.keys())

# summarize history for accuracy
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'validation'], loc='upper left')
plt.show()

# summarize history for loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'validation'], loc='upper left')
plt.show()
dict_keys(['acc', 'val_loss', 'loss', 'val_acc'])

Keras separates the concerns of saving your model architecture and saving your model weights.

Model weights are saved to HDF5 format. This is a grid format that is ideal for storing multi-dimensional arrays of numbers.

The model structure can be described and saved using two different formats: JSON and YAML.

In [40]:
# serialize model to JSON
model_json = model.to_json()
with open("model.json", "w") as json_file:
    json_file.write(model_json)
# serialize weights to HDF5
model.save_weights("model.h5")
print("Saved model to disk")
Saved model to disk
In [41]:
from keras.models import model_from_json

# load json and create model
json_file = open('model.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)

# load weights into new model
loaded_model.load_weights("model.h5")
print("Loaded model from disk")
 
# evaluate loaded model on test data
sgd = SGD(lr=lrate, momentum=0.9, decay=decay, nesterov=False)
loaded_model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])

score = loaded_model.evaluate(X_test, y_test, verbose=0)
print("Accuracy: %.2f%%" % (scores[1]*100))

predictions = loaded_model.predict(X_test)
Loaded model from disk
Accuracy: 91.24%
In [42]:
import random

# show couple of random images from the given set
def plot_examples(preds, features, labels, show_errors=False):
    
    # reverse one hot encoding
    predicted_labels = np.argmax(np.round(preds), axis=1)
    known_labels = np.argmax(labels, axis=1)
    
    # compare model predictions with known labels
    result = (predicted_labels == known_labels)

    indices = [i for i, x in enumerate(result) if x == (not show_errors)]

    # show an image from each class in a grid
    plt.subplots(figsize=(20, 35))
    for i in range(5):
        
        image_id = random.choice(indices)
        # image_id = indices[i]
        
        plt.subplot(150 + 1 + i)
        plt.imshow(toimage(features[image_id]))
        
        label_id = predicted_labels[image_id]
        predicted_title = signnames['SignName'][label_id]
        
        label_id = known_labels[image_id]
        known_title = signnames['SignName'][label_id]

        plt.title("P: {}".format(predicted_title))
        plt.xlabel("C: {}".format(known_title))

Examples of correct predictions:

Let us look at couple of images for which our model got correct Predictions.

Text on the top of the images are the predicted labels, whereas text at the bottom of the imgaes are the true known labels.

In [43]:
plot_examples(predictions, X_test, y_test, False)

Examples of wrong predictions:

Let us also look at couple of images for which our model got predictions wrong.

In [44]:
plot_examples(predictions, X_test, y_test, True)

Question 1

Describe how you preprocessed the data. Why did you choose that technique?

Answer:

I did some Exploratory Data Analysis before commencing. I plotted one image from each class to see what's in the dataset. I also loaded signnames.csv to understand the description of each class. Then I plotted histogram of the image samples by class. I noticed that many of the classes were under represented, which can cause poor performance of the Neural Net.

So I generated additional images in under represented classes by rotating images by small angles. OpenCV has a function, which does this with ease. Another plot of histogram shows that post-generation we have equal number of images in each class.

Then I normalized the values in images(features) from 0-255 to 0.0-1.0 so that variance in the data is low.

I then one-hot encoded the labels, because Neural Net model works well with this format for labels.

Finally, used sklearn's train_test_split function to randomize data and split dataset into training and validation set.

That's it. Our data is preprocessed and ready for ingestion into NN.

Question 2

Describe how you set up the training, validation and testing data for your model. Optional: If you generated additional data, how did you generate the data? Why did you generate the data? What are the differences in the new dataset (with generated data) from the original dataset?

Answer:

I used sklearn's train_test_split function to randomize data and split dataset into training and validation set. I kept aside 20% of the training data for validations. I used test data only for final accuracy reporting of the model.

During Exploratory Data Analysis, I plotted histogram of the image samples by class. I noticed that many of the classes were under represented, which can cause poor performance of the Neural Net. So I generated additional images in under represented classes by rotating images by small angles. OpenCV has a function, which does this with ease. Another plot of histogram shows that post-generation we have equal number of images in each class.

Question 3

What does your final architecture look like? (Type of model, layers, sizes, connectivity, etc.) For reference on how to build a deep neural network using TensorFlow, see Deep Neural Network in TensorFlow from the classroom.

Answer:

My Neural Network has two convolutional layers followed by max pooling and a flattening out of the network to fully connected layers to make predictions.

Network's structure can be summarized as follows:

  • Convolutional input layer, 32 feature maps with a size of 3×3, a rectifier activation function and a weight constraint of max norm set to 3.
  • Dropout set to 20%.
  • Convolutional layer, 32 feature maps with a size of 3×3, a rectifier activation function and a weight constraint of max norm set to 3.
  • Max Pool layer with size 2×2.
  • Flatten layer.
  • Fully connected layer with 512 units and a rectifier activation function.
  • Dropout set to 50%.

Fully connected output layer with 43 units and a softmax activation function.

Question 4

How did you train your model? (Type of optimizer, batch size, epochs, hyperparameters, etc.)

Answer:

To train the network, I used the logarithmic loss function with the stochastic gradient descent optimization algorithm configured with a large momentum and weight decay start with a learning rate of 0.01.

After many tests, and trial and errors, following parameters were used:

  • epochs = 25
  • lrate = 0.01
  • decay = lrate/epochs
  • momentum = 0.9
  • batch_size = 32

Question 5

What approach did you take in coming up with a solution to this problem? It may have been a process of trial and error, in which case, outline the steps you took to get to the final solution and why you chose those steps. Perhaps your solution involved an already well known implementation or architecture. In this case, discuss why you think this is suitable for the current problem.

Answer:

Oh man! Where to begin. This project was full of trials and errors. I was playing with legos of Convolution blocks, Max Pooling blocks and Fully connected blocks.

I started small with few layers and nodes, and slowly built upon it. After some time, adding more convolution layers did not improve results, but increased computation time by a lot. So I scaled back. Besides, Traffic Sign images have low statistical invariance, so too many convolutions steps does not help.

In the end, I settled for a mid size architecture.

I did not use more than 25 epochs because validation accuracy was not improving after that.

Not to mention that I wanted to keep my AWS cost to minimum, so I called 92% test accuracy a success. Moreover, at this accuracy, model was able to correctly predict 5/6 images downloaded from internet. So, I was pretty happy.


Step 3: Test a Model on New Images

Take several pictures of traffic signs that you find on the web or around you (at least five), and run them through your classifier on your computer to produce example results. The classifier might not recognize some local signs but it could prove interesting nonetheless.

You may find signnames.csv useful as it contains mappings from the class id (integer) to the actual sign name.

Implementation

Use the code cell (or multiple code cells, if necessary) to implement the first step of your project. Once you have completed your implementation and are satisfied with the results, be sure to thoroughly answer the questions that follow.

In [115]:
### Load the images and plot them here.
### Feel free to use as many code cells as needed.
from os import listdir
import matplotlib.image as mpimg

images_folder = "images/"
new_images = []

# load new images from a folder
images = listdir(images_folder)
for image in images:
    img = mpimg.imread(images_folder + image)
    new_images.append(img)
    
# convert to numpy array, expected input type of the model
new_images = np.asarray(new_images)

# make predictions from the previously trained model
new_predictions = loaded_model.predict(new_images)

print("Prediction Confidence for respective images:")
print([max(i)*100 for i in np.round(new_predictions, 2)])

# reverse one hot encoding
new_label_ids = np.argmax(np.round(new_predictions), axis=1)

plt.subplots(figsize=(20, 35))

# plot new images with predicted labels on the top
for i, new_label_id in enumerate(new_label_ids):
    predicted_title = signnames['SignName'][new_label_id]
    plt.subplot(160 + 1 + i)
    plt.imshow(new_images[i])
    plt.axis("off")
    plt.title(predicted_title)
Prediction Confidence for respective images:
[73.000001907348633, 100.0, 97.000002861022949, 100.0, 100.0, 100.0]

Question 6

Choose five candidate images of traffic signs and provide them in the report. Are there any particular qualities of the image(s) that might make classification difficult? It could be helpful to plot the images in the notebook.

Answer:

I downloaed the above 6 images from the internet. Then used GIMP to crop and scale images to desired 32x32 size. I then fed these new images to the previously trained model. The predictions for each image is shown on the top of the images.

Most of the images that I found were copy right protected. These images are of very bad quality (pixelated), and would make classification not easy for the model. I also noticed that the one image that my model got wrong, has background and foreground color pretty similar. Could this have caused an issue in our small-ish network?

In the end, 5/6 images were correctly classified. So it looks like we trained our network well :)

Question 7

Is your model able to perform equally well on captured pictures when compared to testing on the dataset? The simplest way to do this check the accuracy of the predictions. For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate.

NOTE: You could check the accuracy manually by using signnames.csv (same directory). This file has a mapping from the class id (0-42) to the corresponding sign name. So, you could take the class id the model outputs, lookup the name in signnames.csv and see if it matches the sign from the image.

Answer:

Model correctly classified 5 out of 6 internet images. Thus resulting in 83.33% accuracy. I have plotted all the internet images above with predicted class labels on the top.

I'm not quite sure, why it got the 6th image wrong. I also noticed that this image has background and foreground color pretty similar. Not a huge contrast for the sign to standout. Could this have caused an issue in our small-ish network?

Model generalizes well with the data from the dataset. Correctly recognizing 5 images from the internet is nothing short of a magic to me. :)

Question 8

Use the model's softmax probabilities to visualize the certainty of its predictions, tf.nn.top_k could prove helpful here. Which predictions is the model certain of? Uncertain? If the model was incorrect in its initial prediction, does the correct prediction appear in the top k? (k should be 5 at most)

tf.nn.top_k will return the values and indices (class ids) of the top k predictions. So if k=3, for each sign, it'll return the 3 largest probabilities (out of a possible 43) and the correspoding class ids.

Take this numpy array as an example:

# (5, 6) array
a = np.array([[ 0.24879643,  0.07032244,  0.12641572,  0.34763842,  0.07893497,
         0.12789202],
       [ 0.28086119,  0.27569815,  0.08594638,  0.0178669 ,  0.18063401,
         0.15899337],
       [ 0.26076848,  0.23664738,  0.08020603,  0.07001922,  0.1134371 ,
         0.23892179],
       [ 0.11943333,  0.29198961,  0.02605103,  0.26234032,  0.1351348 ,
         0.16505091],
       [ 0.09561176,  0.34396535,  0.0643941 ,  0.16240774,  0.24206137,
         0.09155967]])

Running it through sess.run(tf.nn.top_k(tf.constant(a), k=3)) produces:

TopKV2(values=array([[ 0.34763842,  0.24879643,  0.12789202],
       [ 0.28086119,  0.27569815,  0.18063401],
       [ 0.26076848,  0.23892179,  0.23664738],
       [ 0.29198961,  0.26234032,  0.16505091],
       [ 0.34396535,  0.24206137,  0.16240774]]), indices=array([[3, 0, 5],
       [0, 1, 4],
       [0, 5, 1],
       [1, 3, 5],
       [1, 4, 3]], dtype=int32))

Looking just at the first row we get [ 0.34763842, 0.24879643, 0.12789202], you can confirm these are the 3 largest probabilities in a. You'll also notice [3, 0, 5] are the corresponding indices.

Answer:

Following is the Prediction Confidence for each internet images: [73.000001907348633, 100.0, 97.000002861022949, 100.0, 100.0, 100.0]

Model correctly classified 5 out of 6 images. The model is pretty certain of all the images that it got correct. For "Speed limit (80km/hr)", "No Entry", and "Stop" it was 100% certain. For other two, "Speed limit (20km/hr)" and "General caution", model's certainity was less than 100%, but still highest.

The last image - "Left Turn", is most perplexing output. Model is 100% sure that it is a "Roundabout" sign, which is 100% wrong! I'm not quite sure, how to explain this. Time permitting I intend to investigate this further with bigger networks.

Note: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In [ ]: